$(function () {
    var htms=$("#cght_htms").val();
    //alert(htms);
    if(htms=="xxms" || htms==""){
       $("#cght_htmsyc").show();
    }else{
        $("#cght_htmsyc").hide();
    }

    $("#hqmx").click(function () {
        var xhtbm = $("[name='cght.xsxt_htbm']").val();
         if(xhtbm==""){
            // alert("请填写销售系统子项号!");
             $.messager.alert('提示', '请填写销售系统子项号！', 'info');
             return false;
         }

        var url = $.webPath() + "/htgl/cghtgl/hqmxList";

        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: {xhtbm: xhtbm},
            beforeSend: function () {
                $.messager.progress();
            },
            success: function (data) {
                $.messager.progress("close");
             /*   if (data.statusCode == 200) {
                    alert("成功！"+data.list);
                    $("#cght_mx").edatagrid("loadData", {
                        total: 1,
                        rows: data.list
                    })
                }else{*/
                    $("#cght_mx").edatagrid("loadData", {
                        total: 1,
                        rows: data.rows
                    })
                    //alert("异常")
               // }
            }
        });
    });

    $("#cght_lj_id").ljcombobox1({
        onSelect: function (record) {
            $("#cght_hzf_id").cghthzfcombobox({required: true, ljId:record.id});
            $("#cght_lj_id").next().find('.combo-text').ljDetail(record.id);
        }
    });

    //税率的加载
    $('#cght_sl').slsjzdcombobox("sl");
    //仓库加载
    //$("#cght_ck_id").jyckcombobox($("#cght_sbgs_id").val());
    $("#cght_ck_id").combobox({
        url:$.webPath() + '/organ/ck/ywsfckmcList',
        valueField:'id',
        textField:'mc',
        panelHeight:'200',
        editable:true
    });

    //付款方式
    $("[name='cght.fkfs.id']").sjzdcombobox('fkfs');

    //供应商的加载
    $("#cght_hzf_id").cghthzfcombobox({required: true, ljId: $("[name='cght.lj.id']").val()});

    //质押方的加载
    $("#cght_zyf_id").zyfzcombobox({
        onSuccess: function () {
            $("#cght_zyf_id").zcombobox("setMap", { id: $("#zyf_content_id").val(), jc: $("#zyf_content_jc").val()});
        },
        onSelect: function () {
            var id_val = $('#cght_zyf_id').val();
        }
    });

    var cghtId = $("[name='cght.id']").val();
    //合同明细的加载
    if (cghtId) {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
            $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
                mxGrid($.webPath() + '/htgl/cghtgl/cghtgl_htmx?cghtId=' + cghtId || '', cddata, data);
            })
        });

        $("#cght_lj_id").ljcombobox1({
            onSelect: function (record) {
                $("#cght_hzf_id").cghthzfcombobox({required: true, ljId:record.id});
                $("#cght_lj_id").next().find('.combo-text').ljDetail(record.id);
            }
        });
    } else {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
            $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
                mxGrid($.webPath() /*+ '/htgl/cghtgl/bgjhhzmx_htmx?cghtId=' + $("#bgjhhz_id").val()*/ || '', cddata, data);
            })
        });
    }


    //附件的加载
    $("#cght-uploadify").upload('cght-fileQueue', {
        onUploadSuccess: function (file, data, response) {
            var obj = eval('(' + data + ')');
            $("#cght-fileQueue .data").remove();
            $("#cght-fileQueue .uploadify-progress").fadeOut(500, function () {
                $(this).remove();
            });
            $("#" + file.id).append("<input type='hidden' id='cght-file" + obj.fileId + "' name='cght.fjList.id' value='" + obj.fileId + "'/>");
            $("#" + file.id + " .cancel a").bind('click', function () {
                $(this).attr('href', 'javascript:void(0)');
                deleteCghtFile(obj.fileId, file.id);
            });
        }
    });

    // 加载合同模板
    if ($("[name='cght.id']").val()) {
        $("[name='cght_htmb']").htmbcombobox(false, $("[name='htdyId']").val(), {
            onChange: function (oldValue, newValue) {
                // 加载合同文本
                $.ajax({
                    type: "POST",
                    url: $.webPath() + "/htdygl/htwb/htwbDetail",
                    dataType: "html",
                    data: {htmbId: oldValue, htdyId: $("[name='htdyId']").val(), htId: $("[name='cght.id']").val()},
                    beforeSend: function () {
                        $.messager.progress();
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        $('#htwb_cght_id').html(data);
                        if (data.statusCode == 300) {
                        }
                        if (data.statusCode == 200) {
                        }
                    }
                });
            }
        });
        // 如果已经有了文本加载文本
        $.ajax({
            type: "POST",
            url: $.webPath() + "/htdygl/htwb/htwbDetail",
            dataType: "html",
            data: {htdyId: $("[name='htdyId']").val(), htId: $("[name='cght.id']").val()},
            beforeSend: function () {
                $.messager.progress();
            },
            success: function (data) {
                $.messager.progress("close");
                $('#htwb_cght_id').html(data);
            }
        });
    }
    ;
});

function mxGrid(href, cdOptions, fsOptions) {
    $("#cght_mx").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        //fit: true,
        checkbox: false,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        toolbar: "#cghtgl_cghtmx_toolbar",
        columns: [
            [
               // {field: 'wzgg.code', name: 'test', title: '物资编码', width: 50, hidden: true},
                {field: 'wzgg.id', title: 'id', width: 100,hidden: true},
                {field: 'wzgg.name', title: '物资名称', width: 100},
                {field: 'wzgg.ggxh', title: '规格型号', width: 100},
                {field: 'wzgg.cz', title: '材质', width: 70},
                {field: 'wzgg.dw', title: '单位', width: 20},
//                {field:'ck', editor:{type:'text'}, title:'长宽', width:40},
                {field: 'cd.z',
//                    editor: {type: 'combobox', options: {
//                        data: cdOptions,
//                        valueField: 'id',
//                        textField: 'z',
//                        multiple: false,
//                        panelHeight: '150',
//                        enabled: false
//                    }
//                    }, formatter: function (value) {
//                    for (var i = 0; i < cdOptions.length; i++) {
//                        if (cdOptions[i].id == value) return cdOptions[i].z;
//                    }
//                    return value;
//                },
                    title: '产地', width: 40},
                {field: 'sbjs',
//                    editor:{type:'numberbox', options:{min:0, groupSeparator:',', precision:4}},
                    title: '件数',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    },
                    width: 70},
                {field: 'sbsl',
//                    editor:{type:'numberbox', options:{min:0, groupSeparator:',', precision:4}},
                    title: '重量',
                    formatter: function (value) {
                        var sl = formatSlForHtml(value, ",");
                        return sl;
                    },
                    width: 70},
                {field: 'jzfs.z',
//                    editor: {type: 'combobox', options: {
//                    data: fsOptions,
//                    valueField: 'id',
//                    textField: 'z',
//                    multiple: false,
//                    panelHeight: '55',
//                    enabled: false
//                }
//                }, formatter: function (value) {
//                    for (var i = 0; i < fsOptions.length; i++) {
//                        if (fsOptions[i].id == value) return fsOptions[i].z;
//                    }
//                    return value;
//                },
                    title: '记重方式', width: 50},
                {field: 'hsj', /*editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}},*/ title: '含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJeForHtml(value);
                        return sl;
                    }, width: 70},
                {field: 'bhsj', /*editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}},*/ title: '不含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJeForHtml(value);
                        return sl;
                    }, width: 70},
                {field: 'hsje', /*editor: {type: 'numberbox', options: {min: 0, precision: 2, groupSeparator: ','}},*/ title: '含税总金额(元)',
                    formatter: function (value) {
                        var sl = formatJeForHtml2(value);
                        return sl;
                    }, width: 80},
                {field: 'xsxt_xsdh', /*editor: {type: 'text'},*/ title: '销售系统子项号', width: 100},
                {field: 'spec', /*editor: {type: 'text'},*/ title: '特点', width: 100}
            ]
        ]/*,loadFilter: function (datas) {
            $.each(datas.rows, function () {
               // if (this.sbsl)
                // this['sbsl'] = this.sbsl;
                 //this['hsj'] = this.hsj;
                 this['hsje'] = this.sbsl * this.hsj;
                //this.hsje = this.sbsl*this.hsj;
                return datas;
            })
        }*/
        /*,
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#cght_mx").edatagrid('editRow', rowIndex);
            var editors = $("#cght_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var bhsjEditor = editors[1];
            var hsjEditor = editors[0];
            var hsjeEditor = editors[2];
//            var sbslEditor = editors[2];
//            sbslEditor.target.unbind('blur').bind('blur', function () {
//                $(sbslEditor.target).numberbox('setValue', $(sbslEditor.target).val());
//                $(bhsjEditor.target).numberbox('setValue', formatMoneyFourWei(tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#cght_sl").combobox('getValue'))));
//                $(hsjeEditor.target).numberbox('setValue', formatMoney($(hsjEditor.target).numberbox('getValue') * $(sbslEditor.target).numberbox('getValue')))
//                countCghtSum(rowIndex, $(sbslEditor.target).numberbox('getValue'), $(hsjEditor.target).numberbox('getValue'));
//            });
            hsjEditor.target.unbind('blur').bind('blur', function () {
                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());

                var bhsj = formatMoneyFourWei(tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#cght_sl").combobox('getValue')));
                if (!$(bhsjEditor.target).numberbox('getValue'))
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                else if (Math.abs($(bhsjEditor.target).numberbox('getValue') - bhsj) >= 0.01) {
                    $(bhsjEditor.target).numberbox('setValue', bhsj);
                }
                $(hsjeEditor.target).numberbox('setValue', formatMoney($(hsjEditor.target).numberbox('getValue') * rowData.sbsl));//$(sbslEditor.target).numberbox('getValue')));
                countCghtSum(rowIndex, rowData.sbsl, $(hsjEditor.target).numberbox('getValue'));
            });
            bhsjEditor.target.unbind('blur').bind('blur', function () {
                $(bhsjEditor.target).numberbox('setValue', $(bhsjEditor.target).val());
                var hsj = formatMoneyFourWei(tax.getIncludingTaxPrice($(bhsjEditor.target).numberbox('getValue'), $("#cght_sl").combobox('getValue')));
                if (!$(hsjEditor.target).numberbox('getValue'))
                    $(hsjEditor.target).numberbox('setValue', hsj);
                else if (Math.abs($(hsjEditor.target).numberbox('getValue') - hsj) >= 0.01) {
                    $(hsjEditor.target).numberbox('setValue', hsj);
                }
                $(hsjeEditor.target).numberbox('setValue', formatMoney($(hsjEditor.target).numberbox('getValue') * rowData.sbsl));/*//* $(sbslEditor.target).numberbox('getValue')));
                countCghtSum(rowIndex, rowData.sbsl, $(hsjEditor.target).numberbox('getValue'));
            });
        }*/
    })
}


function deleteCghtFile(fileId, id) {
    $.messager.confirm('确认', '是否确认删除此附件', function (r) {
        if (r) {
            $.post($.webPath() + '/base/fj/deleteFj', {'fjId': fileId}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $("#cght-file" + fileId).remove();
                    $("#" + id).fadeOut(500, function () {
                        $(this).remove();
                    });
                }
            });
        }
    })
}


//计算计划总量
function countCghtSum(index, countSbsl, counthsj) {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#cght_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        if (i == index) {
            sbsl = parseFloat(countSbsl);
            hsj = parseFloat(counthsj);
        }
        sbsl = isNaN(sbsl) ? 0.00 : sbsl;
        hsj = isNaN(hsj) ? 0.00 : hsj;
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += hsj * sbsl;
    }
    addFooter(sumsbsl, sumhsj, sumhsje);
}

//计算计划总量
function countSumCg() {
    var sumsbsl = 0;
    var sumhsj = 0;
    var sumhsje = 0;
    var data = $("#cght_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]['sbsl']);
        var hsj = parseFloat(data.rows[i]['hsj']);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        sumsbsl += sbsl;
        sumhsj += hsj;
        sumhsje += hsj * sbsl;
    }
    addFooter(sumsbsl, sumhsj, sumhsje);
}

//页面js合计
function addFooter(sumsbsl, sumhsj, sumhsje) {
    var sumbhsj = 0;
    if ($("#cght_sl")) {
        sumbhsj = tax.getNotIncludingTaxPrice(sumhsj, ($("#cght_sl").combobox('getValue')));
    }
    var footer = [
        {"wzgg.code": "合计", "sbsl": formatMoneyFourWei(sumsbsl), "bhsj": formatMoneyFourWei(sumbhsj), "hsj": formatMoneyFourWei(sumhsj), "hsje": sumhsje}
    ];
    if (footer != null)
        $("#cght_mx").edatagrid('reloadFooter', footer);
}


